<?php

require_once("includes/sparqllib.php");
require_once("model/Dsb.class.php");
require_once("model/Observation.class.php");
require_once("model/Dimension.class.php");
require_once("model/DimensionValue.class.php");
require_once("model/Attribute.class.php");
require_once("model/QueryManager.class.php");
include("model/Dataset.class.php");
include("model/Measure.class.php");
Class uriController Extends baseController {


public $queryManager;


public function index() 
{
        $this->registry->template->uri_heading = 'Enter the Observation URI';
        $this->registry->template->show('ui');
		
		
}


public function view(){
   
        $this->queryManager=QueryManager::GetInstance();
        $this->queryManager->iniConnection($this->parameters['endpoint']);
        $observation=$this->isObservation($this->parameters['uri']);
		
        if(isset($observation)){
        echo '{"status":"ok","observation":'.json_encode($observation).'}';
     
        }
        else{ 
          echo '{"status":"error","msg":"No Observation exists..."}';
 		 }     
        
        
}
public function dataset(){
   

        $this->queryManager=QueryManager::GetInstance();
        $this->queryManager->iniConnection($this->parameters['endpoint']);
        $dataset=$this->getDataSetMetadata($this->parameters['uri']);
	
        if(isset($dataset)){
		//$this->registry->template->dataset = $dataset;
		//$this->registry->template->endpoint = $this->parameters['endpoint'];
        //$this->registry->template->show('dataset_ajax');
		echo '{"status":"ok","dataset":'.json_encode($dataset).'}';
        }
        else{ 
		//$this->registry->template->dataset = null;
        echo '{"status":"error","msg":"No Info exists..."}';
 		 }
        

}

public function traverse(){
		$this->queryManager=QueryManager::GetInstance();
        $this->queryManager->iniConnection($this->parameters['endpoint']);
		$observation=NULL;
		
		$wrappeddim=$this->getWrappedDimensionValues();
		$observation=$this->traverseDimensionObservation($this->parameters['action'],$this->parameters['dim_val'],$this->parameters['measurelab'],$this->parameters['measureuri'],$this->parameters['dim_uri'],$this->parameters['uri'],$wrappeddim);
        
        if(isset($observation)){
        
        	  echo '{"status":"ok","uri":"'.$observation.'"}';
        }
        else{
          
          
		   echo '{"status":"error","msg":"No Observation exists..."}';
          }     
        
        
        

}

public function traversemeasure(){
		$this->queryManager=QueryManager::GetInstance();
        $this->queryManager->iniConnection($this->parameters['endpoint']);
		$observation=NULL;
		$wrappeddim=$this->getWrappedDimensionValues();
		$observation=$this->traverseMeasureObservation($this->parameters['action'],$this->parameters['measurelab'],$this->parameters['measureuri'],$wrappeddim);
        
        if(isset($observation)){
        
        	  echo '{"status":"ok","uri":"'.$observation.'"}';
        }
        else{
          
          
		   echo '{"status":"error","msg":"No Observation exists..."}';
          }     
        
        
        

}
public function traverseMeasureObservation($dir,$measure_lab,$measure_uri,$wrappeddim){

		$this->queryManager=QueryManager::GetInstance();
		$sparql=$this->queryManager->getTraverseMeasureObservationQuery($dir,$measure_lab,$measure_uri,$wrappeddim);
		
		$observation=NUll;
        $result = sparql_query( $sparql ); 
        if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
			if(sparql_num_rows( $result)==0){
				
					$observation=NUll;
			}
			else{
			  
				$row = sparql_fetch_array( $result );
				$observation=$row['uri'];
					
					
				
			}
			
return $observation; 
}
public function dimension_traverse(){
        $this->queryManager=QueryManager::GetInstance();
        $this->queryManager->iniConnection($this->parameters['endpoint']);
		$observations=NULL;
		
		$res=$this->getDimensionObservations($this->parameters['dim_val_uri'],$this->parameters['dim_uri'],$this->parameters['dim_val'],$this->parameters['dim_lab'],$this->parameters['indirect'],$this->parameters['dir']);
        
        if(isset($res)){
		
        $this->registry->template->endpoint=$this->parameters['endpoint'];
        $this->registry->template->areObservations = true;
        $this->registry->template->observations =$res['obs'];
		$this->registry->template->dimension = $res['dim'];
        }
        else{
          
           $this->registry->template->areObservations = false;
           $this->registry->template->notObservation = "No Observations exists... ";
          }     
        
        $this->registry->template->show('uri_dim');
        
}

public function getDataSetMetadata($obs_uri){

       	$this->queryManager=QueryManager::GetInstance();
		$sparql=$this->queryManager->getDataSetMetadataQuery($obs_uri);
		$result = sparql_query( $sparql ); 
		if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
		$row = sparql_fetch_array( $result );
		$dsobject=NULL;
		if(isset($row['ds'])){
		$ds=$row['ds'];
		$label=(isset($row['label'])) ? $row['label'] :$row['title'];  
		$comment=(isset($row['comment'])) ? $row['comment'] : "N/A";  
		$dateds=(isset($row['date'])) ? $row['date'] : "N/A";  
		$subject=(isset($row['subject'])) ? $row['subject'] : "N/A";  
		$publisher=(isset($row['publisher'])) ? $row['publisher'] : "N/A";  
		$dsobject=Dataset::WrapDataset($ds,$label,$comment ,$dateds, $subject, $publisher);
		}	    
		 
 return $dsobject;


}
public function getDimensionObservations($dim_uri_val,$dim_uri,$dim_val,$dim_lab,$indirect,$dir){
        
		$this->queryManager=QueryManager::GetInstance();

		$dim_arr=$this->getRightDimensionValueURI($dim_uri_val,$dim_uri,$dim_val,$dir);
		$dim_uri_dir=$dim_arr['dimvaluri'];
	    $dim_val_dir=$dim_arr['dimval'];
		if(!isset($dim_uri_dir)||!isset($dim_val_dir)){
	
		return NULL;
		}
		else
		{
		$sparql=$this->queryManager->getDimensionObservationsQuery($dim_uri_dir,$dim_uri,$indirect);
		$observations=NUll;
				

        $result = sparql_query( $sparql ); 
        if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
			if(sparql_num_rows( $result)==0){
				   
					$observations=NUll;
			}
			else{
			  $observations=array();
			  while($row = sparql_fetch_array( $result )){
			  
			    if(isset($row['uri']))
			     $observations[]=$row['uri'];
			    
			  }
				
			
			}
	
	    $dimension=Dimension::GetInstance();
		$dimension->valueURI=$dim_uri_dir;
		$dimension->label=$dim_lab;
		$dimension->URI=$dim_uri;
		$dimension->isIndirect=(strcmp($indirect,"0")==0)? true : false;
		$dimension->value=  $dim_val_dir;		
	$res=array('obs'=>$observations,'dim'=>$dimension->copy());
	}
return $res;

}

public function getRightDimensionValueURI($dim_uri_val,$dim_uri,$dim_val,$dir){
		if(strcmp($dir,'none')==0){
				
		$arr=array ('dimvaluri'=>$dim_uri_val,'dimval'=>$dim_val);
		}
		else{
				

		$arr=$this->getDimensionValueURIbyDirection($dim_uri,$dim_val,$dir);
		print_r ($arr);
		}
	
 return $arr;
}
public function getDimensionValueURIbyDirection($dim_uri,$dim_val,$dir){


        $sparql=$this->getDimensionValueURIByDirectionQuery($dim_uri,$dim_val,$dir);
		$dim_uri_dir=NUll;
        $result = sparql_query( $sparql ); 
        if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
			if(sparql_num_rows( $result)==0){
				   
					$dim_uri_dir=NUll;
			}
			else{
			 $row = sparql_fetch_array( $result );
			 
			 $dim_uri_dir=$row;
			}
	
return $dim_uri_dir;


}


public function getWrappedDimensionValues(){
  $uris=preg_split('[,]',$this->parameters['arr_dimuri']);
  $values=preg_split('[,]',$this->parameters['arr_dimval']);
  $labs=preg_split('[,]',$this->parameters['arr_dimlab']);
  $arr_dimvaluri=preg_split('[,]',$this->parameters['arr_dimvaluri']);
  $arr_dimindirect=preg_split('[,]',$this->parameters['arr_dimindirect']);
  $arr_att=preg_split('[,]',$this->parameters['arr_dimatt']);
  $arr_comment=preg_split('[,]',$this->parameters['arr_comment']);

   $dimensionAndValues=array("dimensions"=>array(),"values"=>array());
  for ($i =0 ;$i<count($uris); $i++){
	$isIndirect=(strcmp($arr_dimindirect[$i],"0")==0)? true : false;
    $dim=Dimension::WrapDimention($uris[$i],$labs[$i],$arr_comment[$i],$arr_att[$i],$isIndirect);
	$dimval=DimensionValue::WrapDimentionValue($values[$i],$arr_dimvaluri[$i],"no data available");
	$dimensionAndValues["dimensions"][$i]=$dim;
    $dimensionAndValues["values"][$i]=$dimval;
  }
  
  return $dimensionAndValues;
}
public function traverseDimensionObservation($dir,$dim_val,$msr_lab,$msr_uri,$dim_uri,$ob_uri,$wrappeddim){
        $this->queryManager=QueryManager::GetInstance();
		$sparql=$this->queryManager->getTraverseDimensionObservationQuery($dir,$dim_val,$msr_uri,$dim_uri,$ob_uri,$wrappeddim);
		$observation=NUll;
        $result = sparql_query( $sparql ); 
        if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
			if(sparql_num_rows( $result)==0){
				
					$observation=NUll;
			}
			else{
			  
				$row = sparql_fetch_array( $result );
				$observation=$row['uri'];//$this->combineResults($row ,$dim_val,$msr_lab,$msr_uri,$dim_uri,$ob_uri,$wrappeddim);
					
					
				
			}
			
return $observation;

}



public function createObservationDimension($dsd,$obs){
//TODO : handle comments
  if(isset($dsd->dimensions)){
  for ($i =0 ;$i<count($dsd->dimensions); $i++){
   
    
     $dimValue=$this->getDimensionValue ($dsd->dimensions[$i],$obs);
	 $obs->dimensions[$i]=$dsd->dimensions[$i];
	 $obs->dimensionValue[$i] = $dimValue;
	
	 
	 
  }
}

if(isset($dsd->attributes)){
  for ($i =0 ;$i<count($dsd->attributes); $i++){
   
     $attValue=$this->getAttributeValue ($dsd->attributes[$i],$obs);
	 $obs->attributes[$i]=$dsd->attributes[$i];
	 $obs->attributeValue[$i]=$attValue;
	 
  }
}
}

public function getAttributeValue($att,$obs){

		$this->queryManager=QueryManager::GetInstance();
        $sparql=$this->queryManager->getAttributeValueQuery($att,$obs);
        $result = sparql_query( $sparql ); 
		$attValue=NULL;
		
        if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
			if(sparql_num_rows( $result)==0){
					$attValue=NULL;
			}
			else{
			       
					$row = sparql_fetch_array( $result );
					$attValue1=AttributeValue::GetInstance();
					if(isset($row["attvaluri"])){
					 $attValue1->valueURI=$row["attvaluri"];
					 }
					 else
					 {$attValue1->valueURI="";}
					 if(isset($row["attval"])){
					 $attValue1->value=$row["attval"];
					 }
					 else{
					 $attValue1->value="";
					 }
					 $attValue=$attValue1->copy();
				}
			
		
return $attValue;
}


public function getDimensionValue($dim,$obs){

		$this->queryManager=QueryManager::GetInstance();
        $sparql=$this->queryManager->getDimensionValueQuery($dim,$obs);
        $result = sparql_query( $sparql ); 
		$dimValue=NUll;
		
        if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
			if(sparql_num_rows( $result)==0){
					$dimValue=NULL;
			}
			else{
			       
					$row = sparql_fetch_array( $result );
					$dimValue1=DimensionValue::GetInstance();
					if(isset($row["dimvaluri"])){
					 $dimValue1->valueURI=$row["dimvaluri"];
					 }
					 else
					 {
					 $dimValue1->valueURI="";
					 }
					 if(isset($row["dimval"])){
					 $dimValue1->value=$row["dimval"];
					 }
					 else
					 {
					 $dimValue1->value="";
					 }
					 $dimValue=$dimValue1->copy();
				}
			
			
return $dimValue;

}






public function getStructureDefinition($ob_uri){
         
		$dsdRes=Dsd::GetInstance();
		$dsdRes->dimensions=array();
		$dsdRes->measures=array();
		$dsdRes->attributes=array(); 
		$this->queryManager=QueryManager::GetInstance();
        $sparql1=$this->queryManager->getStructureDefinitionQueryDimension($ob_uri);
		$sparql2=$this->queryManager->getStructureDefinitionQueryAttributes($ob_uri);
        $result1 = sparql_query( $sparql1 ); 
		$result2 = sparql_query( $sparql2 ); 
        if( !$result1 ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
		if( !$result2 ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
			if(sparql_num_rows( $result1)==0 && sparql_num_rows( $result2)==0){
					$dsdRes=NULL;
			}
			else{
			  
					
					
				while($row = sparql_fetch_array( $result1 )){
							
				    $dim=Dimension::GetInstance();
					$attr=Attribute::GetInstance();
					
					$dim->label=$row["dimensionLabel"];
					$dim->URI=$row["dimension"];
							if(isset($row["att"])){
							$dim->isIndirect=true;
							$dim->attachmentLevel=$row["att"];
							}
							else
							{
							$dim->isIndirect=false;
							}
					$dsdRes->dimensions[]=$dim->copy();
			        
                 }

				 while($row = sparql_fetch_array( $result2 )){
						$attr->URI=$row["attribute"];
						//$attr->label=$row["attributeLabel"];
						  if(isset($row["att"])){
							$attr->isIndirect=true;
							$attr->attachmentLevel=$row["att"];
							}
							else
							{
							$attr->isIndirect=false;
							}
						$dsdRes->attributes[]=$attr->copy();
						
					}
					
					
			
			}
			
			
return $dsdRes;

}
public function isObservation($ob_uri){
		$this->queryManager=QueryManager::GetInstance();
        $sparql=$this->queryManager->getIsObservationQuery($ob_uri);
        $result = sparql_query( $sparql ); 
		
        if( !$result ) { print sparql_errno() . ": " . sparql_error(). "\n"; exit; }
			if(sparql_num_rows( $result)==0){
					$isObservationRes=NULL;
			}
			else{
				$isObservationRes=Observation::GetInstance();
				$measure =Measure::GetInstance();
				$isObservationRes->measure=$measure->copy();
				$isObservationRes->observationURI=$ob_uri;	
				while($row = sparql_fetch_array( $result )){
					
					if(strcmp($isObservationRes->measure->label,"")==0){
					$isObservationRes->measure->label=$row["measureLabel"];
					}	
					if(strcmp($isObservationRes->measure->URI,"")==0){
					$isObservationRes->measure->URI=$row["measure"];
					}
					if(strcmp($isObservationRes->observationValue,"")==0){
					$isObservationRes->observationValue=$row["obsValue"];
					}
					
			
				}
				
				$dsd=$this->getStructureDefinition($ob_uri);
				
				
				$this->createObservationDimension($dsd,$isObservationRes);
			}
			
return $isObservationRes;

}






}
?>
